package com.tanchengjin.admin.modules.blog.config.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanchengjin.admin.modules.blog.config.ApiConfig;
import com.tanchengjin.admin.modules.blog.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 *
 * @author TanChengjin
 */
@Configuration
public class JWTInterceptor implements HandlerInterceptor {


    @Autowired
    private ApiConfig apiConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwtHeadName = apiConfig.getJwtHeadName();
        String header = request.getHeader(jwtHeadName);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setStatus(401);
        response.setHeader("Content-Type","Application/json");
        if (header == null || header.isEmpty()) {
            //TODO未认证
            outputStream.write(new ObjectMapper().writeValueAsBytes(new JWTFailureResponse("unauthorized")));
            outputStream.flush();
            outputStream.close();
            return false;
        }
        if(!header.startsWith(apiConfig.getJwtType()))
        {
            outputStream.write(new ObjectMapper().writeValueAsBytes(new JWTFailureResponse("invalid token type")));
            outputStream.flush();
            outputStream.close();
            return false;
        }
        String[] s = header.split(" ");
        String token = s[1];
        if (!JWTUtil.verify(token)) {
            outputStream.write(new ObjectMapper().writeValueAsBytes(new JWTFailureResponse("invalid token")));
            outputStream.flush();
            outputStream.close();
            return false;
        }
        outputStream.close();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
